package com.apkcore.flowlib.flow

import android.util.Log
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.*
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicBoolean

/**
 * @author chanehao
 * @date 2023/03/08
 * @apiNote
 */
class InterceptorController<T>(private val lifecycleOwner: LifecycleOwner) : DefaultLifecycleObserver {
    companion object {
        private const val TAG = "InterceptorController"
    }

    private val mStopped = AtomicBoolean(true)
    private val mPaused = AtomicBoolean(false)
    private var job: Job? = null
    private var curStartRequest: Request? = null

    fun isPaused(): Boolean {
        return mPaused.get()
    }

    fun isStopped(): Boolean {
        return mStopped.get()
    }

    override fun onStop(owner: LifecycleOwner) {
        super.onStop(owner)
        Log.d(TAG, "onStop")
        stop()
    }

    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
        Log.d(TAG, "onCreate")
    }

    override fun onPause(owner: LifecycleOwner) {
        super.onPause(owner)
        pause()
        Log.d(TAG, "onPause")
    }

    override fun onStart(owner: LifecycleOwner) {
        super.onStart(owner)
        Log.d(TAG, "onStart")
//            start(curStartRequest)
    }

    override fun onResume(owner: LifecycleOwner) {
        super.onResume(owner)
        Log.d(TAG, "onResume")
        resume()
    }

    init {
        lifecycleOwner.lifecycle.addObserver(this)
    }

    private val interceptors = mutableListOf<Interceptor<*>>()

    fun addInterceptor(interceptor: Interceptor<*>) {
        interceptors.add(interceptor)
    }

    private val dispatcher = Executors.newFixedThreadPool(2).asCoroutineDispatcher()

    fun start(request: Request?, delayMill: Long = 500) {
        if ((job != null && job?.isActive == true) || interceptors.isEmpty()) {
            return
        }
        mPaused.set(false)
        mStopped.set(false)
        curStartRequest = request
        job = lifecycleOwner.lifecycleScope.launch(dispatcher + CoroutineExceptionHandler { cxt, t ->
            Log.e(TAG, "start: ", t)
        }) {
            while (!isStopped()) {
                try {
                    //暂停
                    if (isPaused()) {
                        delay(1000)
                        continue
                    }
                    execute(request ?: Request())
                    if (delayMill < 0) {
                        break
                    }
                    delay(delayMill)
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
        }
    }

    private suspend fun execute(request: Request) {
        Log.d(TAG, "线程 ${Thread.currentThread().name}")
        val feedbackCollector = mutableListOf<T>()

        // 创建 RealChain 并调用 proceed 方法
        val chain = RealChain(interceptors as List<Interceptor<T>>, 0, feedbackCollector)

        val result = chain.proceed(request)

//            // 打印反馈信息
//            feedbackCollector.reversed().forEach {
//                Log.d(TAG, "Feedback: $it")
//            }
//
//            // 处理最终结果
//            Log.d(TAG, "Final result: $result")

        val (finalRequest, feedbacks) = Pair(result, feedbackCollector.reversed())
        Log.d(TAG, "Final result $finalRequest")
        Log.d(TAG, "feedback: $feedbacks")

    }

    fun stop() {
        mPaused.set(true)
        mStopped.set(true)
        job?.cancel()
        job = null
    }

    fun pause() {
        mPaused.set(true)
    }

    fun resume() {
        mPaused.set(false)
    }
}